const { update, remove, add, getCount, query } = require('../../utils/dbTools')
const { noticeAdd } = require('../../model/notice')
const { getAppointDetail } = require('../../model/appointment')
const { getMemberInfo } = require('../../model/member')
const tableName = 'appointment'
const staffTableName = 'staff'
/**
 * 获取数据总条数
 * 
*/
const appointmentTotal = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { doctor_id } = req.query
    if (!doctor_id) {
        output.code = 500
        output.msg = "参数错误:缺少doctor_id"
        return res.send(output)
    }
    const result = await getCount(tableName, { doctor_id })
    if (!result) {
        output.code = 500
        output.msg = '操作失败'
    }
    output.data = result
    res.send(output)
}

/**
 *  根据医生id||患者id获取预约列表
 * 
*/
const appointmentList = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { doctor_id, patient_id, page, size } = req.query
    if (!doctor_id && !patient_id) {
        output.code = 500
        output.msg = "参数错误:缺少doctor_id和patient_id, 必须提供其中之一"
        return res.send(output)
    }
    // const map = { page, size }
    // const result = await getAll(tableName, map)
    let sql = `select a.id,a.patient_id,a.doctor_id,a.name,a.phone,a.appoint_time,a.status,a.create_time,s.name as doctor,s.phone as doctorPhone`
    sql += ` from ${tableName} a `
    sql += ` inner join ${staffTableName} s on a.doctor_id=s.id`
    if (doctor_id) {
        sql += ` where a.doctor_id=${doctor_id}`
    } else {
        sql += ` where a.patient_id=${patient_id}`
    }
    sql += ` order by a.id desc`
    // 如果传递了分页参数, 则实现分页查询
    if (page && size) {
        sql += `  limit ${(page - 1) * size},${size}`
    }
    const result = await query(sql)
    if (!result) {
        output.code = 500
        output.msg = "操作失败"
        return res.send(output)
    }
    output.data = result
    res.send(output)
}

/**
 * 新增预约信息
 * 
*/

const appointmentAdd = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    let { patient_id, doctor_id, name, phone, appoint_time } = req.body

    if (!patient_id || !doctor_id || !name || !phone || !appoint_time) {
        output.code = 500
        output.msg = "参数错误: 缺少patient_id,doctor_id,name,phone,appoint_time"
        return res.send(output)
    }
    // 将日期字符串(数据库需要的日期格式)
    appoint_time = new Date(appoint_time).toISOString()
    // 查询企业id
    const { bus_id } = await getMemberInfo(doctor_id)
    const data = {
        bus_id, patient_id, doctor_id, name, phone, appoint_time
    }
    const result = await add(data, tableName)
    if (!result) {
        output.code = 500
        output.msg = '操作失败'
        return res.send(output)
    }
    output.data = result
    // 新增通知:医生患者都会收到预约通知
    const datetime = req.body.appoint_time
    const { name: doctorName } = await getStaffInfo(doctor_id)
    const noticeData = {
        title: '预约成功', content: `患者姓名:[${name}]医生姓名:[${doctorName}]预约时间:${datetime}`, option_type: '新增预约', origin_id: result.insertId
    }
    await noticeAdd({ ...noticeData, uid: patient_id })
    await noticeAdd({ ...noticeData, uid: doctor_id })
    res.send(output)
}

/**
 *  删除预约信息
 * 
*/

const appointmentRemove = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }

    const { id } = req.query
    if (!id) {
        output.code = 500
        output.msg = "参数错误"
        return res.send(output)
    }

    const result = await remove(id, tableName)
    if (!result) {
        output.code = 500
        output.msg = "操作失败"
        return res.send(output)
    }
    // 获取预约信息
    const { name, patient_id, doctor_id, doctor: { name: doctorName } } = await getAppointDetail(id)
    const noticeData = {
        title: '取消预约', content: `患者姓名:[${name}]医生姓名:[${doctorName}]取消时间:${Date.now()}`, option_type: '取消预约', origin_id: id
    }
    await noticeAdd({ ...noticeData, uid: patient_id })
    await noticeAdd({ ...noticeData, uid: doctor_id })
    res.send(output)
}

/**
 * 更新预约信息: 仅支持更新状态和时间
*/
const appointmentUpdate = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    let { id, appoint_time, status } = req.body
    if (!id) {
        output.code = 500
        output.msg = "参数错误: 缺少参数id"
        return res.send(output)
    }
    const options = {}
    if (status) {
        options.status = status
    }
    if (appoint_time) {
        // 将日期字符串转为时间戳
        options.appoint_time = new Date(appoint_time).getTime()
    }
    const result = await update(id, options, tableName)
    if (!result) {
        output.code = 500
        output.msg = "操作失败"
        return res.send(output)
    }
    // 获取预约信息
    const { name, patient_id, doctor_id, doctor: { name: doctorName } } = await getAppointDetail(id)
    const noticeData = {
        title: '预约更新', content: `患者姓名:[${name}]医生姓名:[${doctorName}]更新时间:${Date.now()}`, option_type: '更新预约', origin_id: id
    }
    await noticeAdd({ ...noticeData, uid: patient_id })
    await noticeAdd({ ...noticeData, uid: doctor_id })
    res.send(output)
}


/**
 * 获取预约详情
 * id: 预约id
 */
const appointmentInfo = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { id } = req.query
    if (!id) {
        output.msg = '参数错误， 缺少参数id'
        return res.send(output)
    }
    const result = await getAppointDetail(id)
    if (!result) {
        output.code = 500
        output.msg = '未查询到相关数据'
        return res.send(output)
    }
    output.data = result
    res.send(output)
}

module.exports = {
    appointmentAdd,
    appointmentRemove,
    appointmentUpdate,
    appointmentList,
    appointmentTotal,
    appointmentInfo
}